import { ElMessageBox, ElMessage } from "element-plus";
import { emitter } from "@/utils/emitter";

/**
 * 信息弹出框，默认两秒
 */
const msg = {
    //信息弹出框
    info: (message: string, duration: number = 2000) => ElMessage({ showClose: true, message: message, duration: duration }),
    //成功的信息弹出框
    success: (message: string, duration: number = 2000) => ElMessage({ showClose: true, message: message, type: "success", duration: duration }),
    //警告的信息弹出框
    warning: (message: string, duration: number = 2000) => ElMessage({ showClose: true, message: message, type: "warning", duration: duration }),
    //错误的信息弹出框
    error: (message: string, duration: number = 2000) => ElMessage({ showClose: true, message: message, type: "error", duration: duration }),
};

//信息确认框
const box = {
    confirm: (message: string, title: string, callback: any, close: string = `已取消${title}！`) => {
        ElMessageBox.confirm(message, title, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            dangerouslyUseHTMLString: true,
            type: "warning",
            draggable: true,
            autofocus: false,
        })
            .then(callback)
            .catch(() => msg.info(close));
    },
    alert: (message: string, title: string, callback: any, close: string = `已取消${title}！`) => {
        ElMessageBox.alert(message, title, {
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            type: "warning",
            draggable: true,
            autofocus: false,
        })
            .then(callback)
            .catch(() => msg.info(close));
    },
};

/**
 * 弹窗 事件总线
 * @param message 提示信息
 * @param duration 持续时间
 */
emitter.on("msg-info", (payload) => {
    if (typeof payload == "string") {
        msg.info(payload);
    } else {
        msg.info(payload.message, payload?.duration);
    }
});
emitter.on("msg-success", (payload) => {
    if (typeof payload == "string") {
        msg.success(payload);
    } else {
        msg.success(payload.message, payload?.duration);
    }
});
emitter.on("msg-warning", (payload) => {
    if (typeof payload == "string") {
        msg.warning(payload);
    } else {
        msg.warning(payload.message, payload?.duration);
    }
});
emitter.on("msg-error", (payload) => {
    if (typeof payload == "string") {
        msg.error(payload);
    } else {
        msg.error(payload.message, payload?.duration);
    }
});

//暴露
export { msg, box };
